package com.cloud.wms.ui.main.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.multistate.NavIconType;
import com.cloud.core.widget.decoration.GridItemDecoration;
import com.cloud.widget.utils.DensityUtils;
import com.cloud.wms.R;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.base.BaseBarListActivity;
import com.cloud.wms.config.IntentKey;
import com.cloud.wms.tools.BarAdapter;
import com.cloud.wms.ui.main.contract.BaseInfoContract;
import com.cloud.wms.ui.main.entity.MemberEntity;
import com.cloud.wms.ui.main.entity.WarehouseEntity;
import com.cloud.wms.ui.main.presnter.BaseInfoPresenter;
import com.dylanc.loadinghelper.ViewType;
import com.google.android.material.button.MaterialButtonToggleGroup;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * @Author:Chen
 * @Date: 2021-01-18 13:48
 * @Description:
 */
public class BaseInfoActivity extends BaseBarListActivity<WarehouseEntity, BaseInfoPresenter> implements BaseInfoContract.View {
    @BindView(R.id.rg_search_type)
    RadioGroup toggleGroupSearch;
    @BindView(R.id.et_warehouse_member)
    EditText etWarehouseMember;
    @BindView(R.id.tv_warehouse_name)
    TextView tvWarehouseName;
    @BindView(R.id.recyclerView_right)
    RecyclerView recyclerViewRight;
    private boolean isSearchWarehouse = true;
    private BaseQuickAdapter<MemberEntity, BaseViewHolder> adapterRight;
    private WarehouseEntity warehouseEntity;
    private MemberEntity memberEntity;
    private ArrayList<WarehouseEntity> warehouseList = new ArrayList<>();
    private ArrayList<MemberEntity> memberList = new ArrayList<>();
    private boolean isLockWarehouse;

    @Override
    protected String barTitle() {
        return "仓库会员";
    }

    @Override
    protected int getResId() {
        return R.layout.activity_main_base_info;
    }

    @Override
    protected int getItemResId() {
        return R.layout.item_base_info;
    }

    protected void initToolBar() {
        loadingHelper.register(ViewType.TITLE, new BarAdapter(barTitle(), NavIconType.BACK, false));
        loadingHelper.setDecorHeader(ViewType.TITLE);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        isLockWarehouse = getIntent().getBooleanExtra(IntentKey.TYPE_KEY, false);
        toggleGroupSearch.setOnCheckedChangeListener((group, checkedId) -> {
            etWarehouseMember.setText("");
            isSearchWarehouse = checkedId == R.id.rb_warehouse;
        });

        warehouseEntity = FineExApplication.component().loginCache().getWarehouseInfo();
        memberEntity = FineExApplication.component().loginCache().getMemberInfo();

        recyclerViewRight.setLayoutManager(new LinearLayoutManager(this));
        adapterRight = new BaseQuickAdapter<MemberEntity, BaseViewHolder>(R.layout.item_base_info_member) {
            @Override
            protected void convert(BaseViewHolder helper, MemberEntity item) {
                helper.setText(R.id.tv_info_code, item.getMemberNo())
                        .setText(R.id.tv_info_name, item.getMemberName());
                if (memberEntity != null && memberEntity.getMemberID() == item.getMemberID()) {
                    helper.setTextColor(R.id.tv_info_code, ContextCompat.getColor(BaseInfoActivity.this, R.color.font_white))
                            .setTextColor(R.id.tv_info_name, ContextCompat.getColor(BaseInfoActivity.this, R.color.font_white));
                    helper.setBackgroundColor(R.id.ly_item_area, getResources().getColor(R.color.btn_blue));
                } else {
                    helper.setTextColor(R.id.tv_info_name, ContextCompat.getColor(BaseInfoActivity.this, R.color.font_black));
                    helper.setBackgroundColor(R.id.ly_item_area, getResources().getColor(R.color.bg_content));
                }
            }
        };
        adapterRight.setOnItemClickListener((adapter, view, position) -> {
            MemberEntity entity = (MemberEntity) adapter.getData().get(position);
            if (this.memberEntity != null && this.memberEntity.getMemberID() == entity.getMemberID()) {
                memberEntity = new MemberEntity();
            } else {
                memberEntity = entity;
            }
            adapter.notifyDataSetChanged();
        });
        recyclerViewRight.setAdapter(adapterRight);
        mPresenter.loadWarehouseList();

        etWarehouseMember.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isSearchWarehouse) {
                    searchWarehouse(s);
                } else {
                    searchMember(s);
                }
            }
        });
    }

    @Override
    protected void bindItemData(BaseViewHolder helper, WarehouseEntity item) {
        boolean isSelect = warehouseEntity != null && warehouseEntity.getWarehouseID() == item.getWarehouseID();
        helper.setText(R.id.tv_info_code, item.getWareHouseCode())
                .setText(R.id.tv_info_name, item.getWareHouseName());
        if (isSelect) {
            helper.setTextColor(R.id.tv_info_name, ContextCompat.getColor(BaseInfoActivity.this, R.color.font_blue));
            helper.setBackgroundResource(R.id.ly_item_area, R.drawable.bg_base_info);
        } else {
            helper.setTextColor(R.id.tv_info_name, ContextCompat.getColor(BaseInfoActivity.this, R.color.font_black));
            helper.setBackgroundResource(R.id.ly_item_area, R.drawable.bg_base_info_normal);
        }
    }

    @Override
    protected RecyclerView.ItemDecoration itemDecoration() {
        return GridItemDecoration.newBuilder().spanCount(1)
                .verticalDivider(ContextCompat.getDrawable(this, R.color.line), DensityUtils.Dp2Px(this, 1), false)
                .build();
    }

    @Override
    protected void itemClickListener(BaseQuickAdapter<WarehouseEntity, BaseViewHolder> mAdapter, View view, int position) {
        super.itemClickListener(mAdapter, view, position);
        if (isLockWarehouse) {
            info("当前仓库不可变更");
            return;
        }
        warehouseEntity = mAdapter.getItem(position);
        tvWarehouseName.setText(((WarehouseEntity) mAdapter.getItem(position)).getWareHouseName());
        mPresenter.loadMemberList(warehouseEntity.getWarehouseID(), false);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

    @SuppressLint("CheckResult")
    private void searchWarehouse(Editable s) {
        if (TextUtils.isEmpty(s)) {
            long warehouseId = warehouseEntity.getWarehouseID();
            for (int i = 0; i < warehouseList.size(); i++) {
                if (warehouseId == warehouseList.get(i).getWarehouseID()) {
                    tvWarehouseName.setText(warehouseList.get(i).getWareHouseName());
                    scrollToPosition(rvList, i);
                    break;
                }
            }
            mAdapter.setNewInstance(warehouseList);
            return;
        }
        Observable.fromIterable(warehouseList)
                .filter(warehouseInfo -> TextUtils.isEmpty(s) || warehouseInfo.getWareHouseName().contains(s))
                .toList()
                .subscribe(data -> mAdapter.setNewInstance(data));
    }

    @SuppressLint("CheckResult")
    private void searchMember(Editable s) {
        if (TextUtils.isEmpty(s)) {
            long memberID = memberEntity.getMemberID();
            for (int i = 0; i < memberList.size(); i++) {
                if (memberID == memberList.get(i).getMemberID()) {
                    scrollToPosition(recyclerViewRight, i);
                    break;
                }
            }
            adapterRight.setNewInstance(memberList);
            return;
        }
        Observable.fromIterable(memberList)
                .filter(info -> TextUtils.isEmpty(s) || info.getMemberName().contains(s))
                .toList()
                .subscribe(data -> adapterRight.setNewInstance(data));
    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case BaseInfoPresenter.WAREHOUSE:
                setWarehouseData((List<WarehouseEntity>) message.obj);
                break;
            case BaseInfoPresenter.MEMBER:
                setMemberData((List<MemberEntity>) message.obj);
                break;
            case BaseInfoPresenter.STRATEGY:
                success("仓库会员选择成功！");
                this.finish();
                break;
        }
    }

    private void setWarehouseData(List<WarehouseEntity> list) {
        for (int i = 0; i < list.size(); i++) {
            if (warehouseEntity.getWarehouseID() == list.get(i).getWarehouseID()) {
                scrollToPosition(rvList, i);
                tvWarehouseName.setText(list.get(i).getWareHouseName());
                mPresenter.loadMemberList(warehouseEntity.getWarehouseID(), false);
                break;
            }
        }
        warehouseList.clear();
        warehouseList.addAll(list);
        mAdapter.setNewInstance(list);
    }

    private void setMemberData(List<MemberEntity> list) {
        if (memberEntity != null) {
            long memberId = memberEntity.getMemberID();
            for (int i = 0; i < list.size(); i++) {
                if (memberId == list.get(i).getMemberID()) {
                    scrollToPosition(recyclerViewRight, i);
                    break;
                }
            }
        }
        memberList.clear();
        memberList.addAll(list);
        adapterRight.setNewInstance(list);
    }

    @OnClick(R.id.btn_save)
    public void onViewClicked() {
        FineExApplication.component().loginCache().setWarehouseInfo(warehouseEntity);
        if (memberEntity.getMemberID() > 0) {
            FineExApplication.component().loginCache().setMemberInfo(memberEntity);
        }
        mPresenter.loadStrategyList();
    }

    public static void start(Context context, boolean isLockWarehouse) {
        Intent intent = new Intent(context, BaseInfoActivity.class);
        intent.putExtra(IntentKey.TYPE_KEY, isLockWarehouse);
        context.startActivity(intent);
    }
}
